#include <boost/thread.hpp>


#include "Services.h"
#include "Common.h"
namespace RisingStar
{
	CServices::CServices(size_t poolSize,size_t maxPoolSize):mMinServiceCount(poolSize),
															mMaxServiceCount(maxPoolSize)
	{
		//创建（poolSize +1）个服务容量的服务池
		for (size_t i = 0; i < poolSize + 1; ++ i)
        {
			AddService();
        }
		
	}
	CServices::~CServices()
	{
		

	}
	bool CServices::AddService()
	{
//		_EVENT("增加一个服务");

		CTask t;
		mServices.push_back(t);

		return true;
	}
	size_t CServices::GetFreeServiceCount()//获取服务数
	{
		boost::mutex::scoped_lock lock(mMutex);
		return mServices.size();
	}
	
	IOServicePtr& CServices::GetServicePtr()
	{
		boost::mutex::scoped_lock lock(mMutex);
		
		mServicesUsed.push_back(mServices.back());

		mServices.pop_back();

		//如果空闲服务器数量 < mMinServiceCount,增加服务器
		if(mServices.size() < mMinServiceCount)
		{
			AddService();
			//增加服务器
		}
		
		return mServicesUsed[mServicesUsed.size()-1].ioServicePtr;	/**/
	}
	
	bool CServices::Start()
	{
	/*	for (size_t i = 0; i < mServices.size(); ++ i)
        {
			//创建一个boost线程,回调函数是mIOServices[i]内部的，asio::io_service::run，参数没有
            ThreadPtr pThread(new boost::thread(bind(&asio::io_service::run, mServices[i].ioServicePtr)));
			
			//加入到线程库内
            mThreads.push_back(pThread);
        }*/
		
		return true;
	}
    bool CServices::Join()
    {
        for (size_t i = 0; i < mServices.size(); ++ i)
        {
            mServices[i].threadPtr->join();
        } 
    }	
	
	bool CServices::Stop()
	{		
		for (size_t i = 0; i < mServices.size(); ++ i)
        {
           // mServices[i]->stop();
        }
	}
	
	bool CServices::ProcessFreeService()
	{
		vector<CTask>::iterator lIter;

		int i = 0;

		for(lIter = mServicesUsed.begin();lIter != mServicesUsed.end();++lIter,++i)
		{
			
			if((*lIter).ioServicePtr.use_count() < 3)
			{
				//先停止三秒
				sleep(3);
				boost::mutex::scoped_lock lock(mMutex);
				//仍然为1
				if((*lIter).ioServicePtr.use_count() < 3)
				{
					//服务数量检测
					//如果空闲服务器数量  > mMinServiceCount + 1 + 已经使用的服务器
					if( mServices.size()  + 1 < mServicesUsed.size() +  mMinServiceCount)
					{
						mServices.push_back(*lIter);	
						_ERROR("重新利用了服务器");
						//减少服务器
					}
					else
					{
						_ERROR("删除了服务器");
						(*lIter).ioServicePtr->stop();
						(*lIter).threadPtr->join();
						_ERROR("删除服务器成功");

					}

					mServicesUsed.erase(lIter);
					
					break;


				}
			}
			this_thread::yield();
		}
		
	}
}